<?php

namespace app\api\logic;

use app\api\model\Common;
use TencentCloud\Cdn\V20180606\Models\Cache;
use TencentCloud\Cfw\V20190904\Models\DnsVpcSwitch;
use think\cache\driver\Redis;
use think\facade\Db;

class LogicalProcess
{

    /**
     * 代币变更
     * @param $uid  用户id
     * @param $amount 变动金额
     * @param $type 变动类别 类别 1:游戏奖金 2:投注游戏 3:挖矿所得 4：推荐用户返佣 5:释放邀请 6：购买商品获得 7抽卡 8 转赠
     * @param $change 增减  1 增加 2减少
     * @param $currency 代币 1宝石 2勋章
     * @param $brief  备注
     */
    public function wallletChange($uid, $amount, $type, $change, $currency, $brief)
    {
        Db::startTrans();
        try {
            $user = Db::name("user_wallet")->where('user_id', $uid)->where("type", $currency)->lock(true)->find();
            if (empty($user)) {
                Db::rollback();
                return true;
            }
            //获取当前金额
            $old_amount = $user['amount'];
            if ($change == 1) {
                $new_amount = $old_amount + $amount;
            } else {
                $new_amount = $old_amount - $amount;
            }

            Db::name("user_wallet")->where('user_id', $uid)->save(["amount" => $new_amount]);
            Db::name("member_wallet_log")->insert([
                "uid" => $uid,
                "before_price" => $old_amount,
                "after_price" => $new_amount,
                "amount" => $amount,
                "type" => $type,
                "brief" => $brief,
                "category" => $currency,
                "create_time" => time(),
                "change" => $change,
            ]);
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            $error = $e->getMessage();
            return false;
        }
    }

    //挖矿收益查询
    public function queryEarnings($userId)
    {
        //查询玩家拥有的悟空
        $userNpc = Db::name("user_npc")->where("user_id", $userId)->where('npc_id', 1)->whereNotNull("activate_time")->find();
        if (empty($userNpc)) return ['code' => -1, "msg" => "玩家暂未拥有悟空或未激活悟空"];
        $lv = $userNpc['lv'];
        // 获取挖矿配置
        $miningConfig = Db::name("mining_config")->where("id", 1)->find();
        if (empty($miningConfig)) return ['code' => -1, "msg" => "经书配置异常，请联系管理员"];
        //获取数量
        $amount = $miningConfig['amount'];
        //查询每秒收益
        $amountBySecoond = bcdiv($amount, 60 * 60, 6);
        //查询用户上次领取时间
        $getRecord = Db::name("user_get_record")->where("user_id", $userId)->order("create_time desc")->find();
        if (empty($getRecord)) {
            $diffTime = time() - strtotime($userNpc["activate_time"]);
        } else {
            $diffTime = time() - $getRecord['create_time'];
        }
        $amountTotal = bcmul($amountBySecoond, $diffTime, 6);
        if ($amountTotal <= 0) {
            $amountTotal = 0;
        }
        //每日可产
        $thirtyEarnings = bcmul($amountTotal, 60 * 60 * 24, 6);
        $array = [
            1 => $miningConfig["lv_one_efficiency"],
            2 => $miningConfig["lv_two_efficiency"],
            3 => $miningConfig["lv_three_efficiency"],
            4 => $miningConfig["lv_four_efficiency"],
            5 => $miningConfig["lv_five_efficiency"],

        ];
        $amountTotal = bcmul($amountTotal, $array[$lv], 6);
        $thirtyEarnings = bcmul($thirtyEarnings, $array[$lv], 6);
        return ['code' => 0, 'msg' => "操作成功", "data" => ['amountTotal' => $amountTotal, 'thirtyEarnings' => $thirtyEarnings, 'lv' => $lv, 'amountBySecond' => $amountBySecoond]];
    }

    public function GetAccessToken()
    {
//        $str = '{"refresh_token":"25.9382f3a17a61243b2be1d253d315848f.315360000.2047553704.282335-116174183","expires_in":2592000,"session_key":"9mzdCrchY14IIIsCfLuSWqqD6g3mpmnF0G\/F\/I+NNyQzFCy6dNpUALlVvdYfcFP18FaCONlSd2v6q75vEzqr8Fc3gxeZ0C0=","access_token":"24.1337c1e3366b8b02f0ad482373e7040e.2592000.1734785704.282335-116174183","scope":"public brain_all_scope solution_face ai_custom_pro_apple ai_custom_testface1 ai_custom_kouzhaorenlianshibie ai_custom_chongwugou wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\u6743\u9650 vis-classify_flower lpq_\u5f00\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\u5f00\u653eScope vis-ocr_\u865a\u62df\u4eba\u7269\u52a9\u7406 idl-video_\u865a\u62df\u4eba\u7269\u52a9\u7406 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx","session_secret":"6f424fab6dae761800a793776ad11358"}';
//        $res = json_decode($str,true);
//        var_dump($res['access_token']);
//        exit;


        $ak = env("baidu.ak");
        $sk = env("baidu.sk");
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://aip.baidubce.com/oauth/2.0/token?client_id=$ak&client_secret=$sk&grant_type=client_credentials",
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Accept: application/json'
            ),

        ));
        $response = json_decode(curl_exec($curl), true);
        curl_close($curl);

        \think\facade\Cache::store("redis")->set('baidu_token', $response['access_token']);
        return $response;
    }

    public function solutionVerify($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = json_decode(curl_exec($curl),true);
        curl_close($curl);
        return $data;
    }

    public function authVerify($mobile,$name,$idcard)
    {
        $host = "https://kzmobilev2.market.alicloudapi.com";
        $path = "/api/mobile_three/check";
        $method = "POST";
        $appcode = "a518452255984774b573f39f51a7d6ed";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "";
        $bodys = "mobile=$mobile&name=$name&idcard=$idcard";
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        return json_decode(curl_exec($curl),true);
    }

}